<?php
class Authentication
{
	public function login(VOUser $param)
	{
		$dbi = new Dbi();
		if($dbi->mysqli == FALSE && PRODUCTION == FALSE){
			return $dbi->error;
		}
		
		$email = $param->userEmail;
		$password = $param->userPassword;
		$query = "SELECT userId FROM users WHERE userEmail = '$email' AND userPassword = '$password'";
		$result = $dbi->fetchSingleItem($query);
		
		if($result instanceof VOSqlError){
			
			$ret = $result;
			
		} else if(!$result){
			
			$serviceError = new VOServiceError();
			$serviceError->error = TRUE;
			$serviceError->errorCode = 10001;
			$serviceError->errorString = "Bad Credential";
			$serviceError->errorDesc = "Invalid username or password";
			$ret = $serviceError;
			
		} else {
			$userSession = new VOUserSession();
			$userSession = $this->setUserSession($result);
			$ret = $userSession;
		}
		return $ret;
	}
	
	public function signout($userId){
		$dbi = new Dbi();
		if($dbi->mysqli == FALSE && PRODUCTION == FALSE){
			return $dbi->error;
		}
		
		$query = "DELETE FROM user_sessions WHERE userId = $userId";
		$result = $dbi->execute($query);
		return $result;
	}
	
	private function setUserSession($userId){
		$dbi = new Dbi();
		if($dbi->mysqli == FALSE && PRODUCTION == FALSE){
			return $dbi->error;
		}
		
		$secretToken = md5($userId.time());
		
		$profileQuery = "SELECT COUNT(userId) FROM user_profiles WHERE userId = $userId";
		$profileResult = $dbi->fetchSingleItem($profileQuery);
		
		if($profileResult){
			$userHasProfile = 1;
		} else {
			$userHasProfile = 0;
		}
		
		$shopQuery = "SELECT COUNT(userId) FROM user_has_shop_lots WHERE userId = $userId";
		$shopResult = $dbi->fetchSingleItem($shopQuery);
		if($shopResult){
			$userHasShop = 1;
		} else {
			$userHasShop = 0;
		}
		
		$checkQuery = "SELECT userId FROM user_sessions WHERE userId = $userId";
		$checkResult = $dbi->fetchSingleItem($checkQuery);
		if($checkResult){
			$query = "UPDATE user_sessions SET userSecretToken = '$secretToken', userHasProfile = $userHasProfile,
			          userHasShopLots = $userHasShop WHERE userId = $userId";
		} else {
			$query = "INSERT INTO user_sessions(userId, userSecretToken, userHasProfile, userHasShopLots) 
					  VALUES($userId, '$secretToken', $userHasProfile, $userHasShop)";
		}
		
		//Execute
		$result = $dbi->execute($query);
		$sessionStatus = $result->result;
		
		if($sessionStatus){
			$ret = new VOUserSession();
			$ret->userId = $userId;
			$ret->userHasProfile = $userHasProfile;
			$ret->userHasShopLots = $userHasShop;
			$ret->userSecretToken = $secretToken;
		} else {
			$ret = $result;
		}
		
		return $ret;
	}
}
?>